/**
 * Copyright 2016 vip.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * </p>
 **/

package spring.cloud.tasks.api.database.service.impl;

//import org.apache.commons.io.IOUtils;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import spring.cloud.tasks.api.database.entity.TaskConfigurationDto;
import spring.cloud.tasks.api.database.repository.TaskConfigurationDtoRepository;
import spring.cloud.tasks.api.database.service.HistoryTaskConfigurationDtoService;
import spring.cloud.tasks.api.database.service.TaskConfigurationDtoService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TaskConfigurationDtoServiceImpl implements TaskConfigurationDtoService {

    @Resource
    private HistoryTaskConfigurationDtoService historyTaskConfigurationDtoService;

    @Autowired
    private TaskConfigurationDtoRepository taskConfigurationDtoRepository;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int create(TaskConfigurationDto taskConfigurationDto) throws RuntimeException {
        return taskConfigurationDtoRepository.insert(taskConfigurationDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteByPrimaryKey(Long id) throws RuntimeException {
        return taskConfigurationDtoRepository.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateByPrimaryKey(TaskConfigurationDto taskConfigurationDto) throws RuntimeException {
        return taskConfigurationDtoRepository.updateByPrimaryKey(taskConfigurationDto);
    }

    @Override
    public void batchUpdatePreferList(List<TaskConfigurationDto> taskConfigurationDtoList) throws RuntimeException {
        SqlSession batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            for (TaskConfigurationDto taskConfigurationDto : taskConfigurationDtoList) {
                batchSqlSession.getMapper(TaskConfigurationDtoRepository.class).updatePreferList(taskConfigurationDto);
            }
            batchSqlSession.commit();
        } catch (Exception e) {
            batchSqlSession.rollback();
            throw new RuntimeException("error when batchUpdatePreferList", e);
        } finally {
            //IOUtils.closeQuietly(batchSqlSession);
        }
    }

    @Override
    public TaskConfigurationDto getTaskConfigurationDtoByNameSpaceAndTaskId(String namespace, String jobName)
            throws RuntimeException {
        return taskConfigurationDtoRepository.getTaskConfigurationDtoByNameSpaceAndTaskId(namespace, jobName);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateNewAndSaveOld2History(final TaskConfigurationDto newTaskConfigurationDto, final TaskConfigurationDto oldTaskConfigurationDto, final String userName) throws RuntimeException {
        // 持久化当前配置
        if (userName != null) {
            newTaskConfigurationDto.setLastUpdateBy(userName);
        }
        newTaskConfigurationDto.setLastUpdateTime(new Date());
        updateByPrimaryKey(newTaskConfigurationDto);

        // 持久化历史配置
        oldTaskConfigurationDto.setId(null);
        historyTaskConfigurationDtoService.create(oldTaskConfigurationDto);
    }


    @Override
    public List<TaskConfigurationDto> getTaskConfigurationDtoListByNamespace(String namespace) throws RuntimeException {
        return taskConfigurationDtoRepository.getTaskConfigurationDtoListByNamespace(namespace);
    }

    @Override
    public List<TaskConfigurationDto> getTaskConfigurationDtoListByNamespaceWithCondition(String namespace, Map<String, Object> condition,
                                                                                          Pageable pageable) throws RuntimeException {
        return taskConfigurationDtoRepository.getTaskConfigurationDtoListByNamespaceWithCondition(namespace, condition, pageable);
    }

    @Override
    public int countTaskConfigurationDtoByNamespaceWithCondition(String namespace, Map<String, Object> condition)
            throws RuntimeException {
        return taskConfigurationDtoRepository.countTaskConfigurationDtoByNamespaceWithCondition(namespace, condition);
    }

    @Override
    public int countEnabledUnSystemJobsByNamespace(String namespace) throws RuntimeException {
        return taskConfigurationDtoRepository.countEnabledUnSystemJobsByNamespace(namespace, 1);
    }

    @Override
    public List<String> findConfigNamesByNameSpace(String namespace) throws RuntimeException {
        return taskConfigurationDtoRepository.findConfigNamesByNamespace(namespace);
    }


    @Override
    public List<String> findHasValidJobNamespaces(String jobType, int isEnabled) {
        return taskConfigurationDtoRepository.findHasValidJobNamespaces(jobType, isEnabled);
    }

    @Override
    public List<TaskConfigurationDto> findValidJobsCronConfig() {
        return taskConfigurationDtoRepository.findValidJobsCronConfig();
    }
}
